package com.xqyq.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xqyq.model.Admin;
import com.xqyq.model.User;
import com.xqyq.service.AdminService;
import com.xqyq.service.UserService;
import com.xqyq.util.CommonUtil;

@Controller
public class LoginRegisterController {
	@Autowired
	private UserService userService;
	@Autowired
	private AdminService adminService;

	@RequestMapping("/managelogin.html")
	public String manageLogin() {
		return "manage/login";
	}

	@RequestMapping("/api_managelogin")
	@ResponseBody
	public String login(HttpServletRequest request) {
		if (!CommonUtil.isEmpty(request.getParameter("login_name"))
				|| !CommonUtil.isEmpty(request.getParameter("password"))) {
			Admin admin = new Admin();
			admin.setLogin_name(request.getParameter("login_name"));
			admin.setPassword(request.getParameter("password"));
			if (adminService.login(admin, request) == true) {
				return "{\"state\":200,\"comment\":\"登录成功\",\"goPage\":\"manage/index.html\"}";
			} else {
				return "{\"state\":104,\"comment\":\"账号密码不正确。\",\"goPage\":\"\"}";
			}
		} else {
			return "{\"state\":104,\"comment\":\"账号密码不能为空。\",\"goPage\":\"\"}";
		}
	}

	@RequestMapping("/manage/api_loginout")
	public String manageloginout(HttpServletRequest request) {
		request.getSession().setAttribute("admin", null);
		return "redirect:managelogin.html";
	}

	@RequestMapping("/login.html")
	public String login() {
		return "front/login";
	}

	@RequestMapping("/api_login")
	@ResponseBody
	public String api_login(User user, HttpServletRequest request) {
		System.out.println(user.getMail() + user.getPassword());
		user = userService.login(user);
		if (user != null) {
			request.getSession().setAttribute("user", user);
			return "{\"state\":200,\"message\":\"登录成功。\",\"goPage\":\"toHome\"}";
		} else {
			return "{\"state\":104,\"message\":\"账号或密码错误。\",\"goPage\":\"\"}";
		}
	}

	@RequestMapping("/register.html")
	public String register() {
		return "front/register";
	}

	@RequestMapping("/api_register")
	@ResponseBody
	public String api_register(User user, HttpServletRequest request) {
		System.out.println(user);
		user.setStudentId(request.getParameter("studentId"));
		user = userService.register(user);
		if (user != null) {
			request.getSession().setAttribute("user", user);
			return "{\"state\":200,\"message\":\"登录成功。\",\"goPage\":\"login.html\"}";
		} else {
			return "{\"state\":104,\"message\":\"账号已被注册。\",\"goPage\":\"\"}";
		}
	}

	@RequestMapping("/user/api_loginout")
	public String loginout(HttpServletRequest request) {
		request.getSession().setAttribute("user", null);
		return "redirect:homepage.html";
	}

}
